﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using System.IO;
using System.Text;
using Quartz;

namespace QuartzJob.JobWork
{
    // 1. 创建一个向文本文件中插入文字的方法 （注意 必须继承 IJob，要做的事情写在 Execute 中）
    public class SendMessageJob : IJob
    {
        static readonly string path;
        static SendMessageJob()
        {
            path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "log/msg.txt");
        }

        public async Task Execute(IJobExecutionContext context)
        {
            dirExists();

            var msg = $"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")} | 发送消息。。";

            await Task.Run(() =>
            {
                using (StreamWriter sw = new StreamWriter(path, true, Encoding.Default))
                {
                    sw.WriteLine(msg);
                    sw.Close();
                    sw.Dispose();
                }
            });
        }

        private void dirExists()
        {
            var dir = Path.GetDirectoryName(path);
            if (!Directory.Exists(dir))
                Directory.CreateDirectory(dir);
        }
    }
}